package com.lzs.esubscribe.service.impl;

import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;
import com.lzs.esubscribe.dto.*;
import com.lzs.esubscribe.entity.ESUser;
import com.lzs.esubscribe.mapper.UrlMapper;
import com.lzs.esubscribe.mapper.UserMapper;
import com.lzs.esubscribe.service.IUrlService;
import com.lzs.esubscribe.service.IUserService;
import com.lzs.esubscribe.utils.FileUtils;
import com.lzs.esubscribe.utils.TimeStampUtils;
import com.lzs.esubscribe.utils.UuidDoUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author: lzs
 * @Date: 2022-02-17
 * @Description：资源接口实现
 */
@Service("IUrlService")
public class UrlServiceImpl implements IUrlService {
    @Autowired
    UuidDoUtils uuidDoUtils;
    @Autowired
    TimeStampUtils timeStampUtils;
    @Autowired
    UrlMapper urlMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    FileUtils fileUtils;

    private static final Log log = LogFactory.getLog(UrlServiceImpl.class);

    @Override
    public int addUrl(AddUrlDTO addUrlDTO) {
        if (addUrlDTO.getName() == null || addUrlDTO.getBelong() == null || (addUrlDTO.getType() != 1 && addUrlDTO.getType() != 0)) {
            return 0;
        }

        Map<String, Object> addMap = new HashMap<>();
        addMap.put("uuid", uuidDoUtils.uuidDoGenerate());
        addMap.put("name", addUrlDTO.getName());
        addMap.put("url", addUrlDTO.getUrl());
        addMap.put("parent", addUrlDTO.getParent());
        addMap.put("type", addUrlDTO.getType());
        addMap.put("belong", addUrlDTO.getBelong());
        addMap.put("creat_time", timeStampUtils.getTimestamp());
        addMap.put("update_time", timeStampUtils.getTimestamp());
        addMap.put("icon", addUrlDTO.getIcon());

        // 添加资源
        int res = urlMapper.addUrl(addMap);
        return res;
    }

    @Override
    public ImportResultDTO importSubscribe(ImportSubscribeDTO importSubscribeDTO) {
        // 检验用户存在
        if (userMapper.checkUserUuidExist(importSubscribeDTO.getUuid()) == 0) {
            return null;
        }

        // 循环变量
        int i = 0, j = 0;
        int successNum = 0, failNum = 0;

        // 读取文件流为字符串
        List<String> html = null;
        try {
            html = fileUtils.readFileToString(importSubscribeDTO.getFile());
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 正则匹配
        String patternGroup = "<DT><H3 ADD_DATE=\"(.+)\" LAST_MODIFIED=\"(.+)\".*>(.+)</H3>";
        String patternUrlIconExist = "<DT><A HREF=\"(.+)\" ADD_DATE=\"(.+)\" ICON=\"(.+)\">(.+)</A>";
        String patternUrlIconNotExist = "<DT><A HREF=\"(.+)\" ADD_DATE=\"(.+)\">(.+)</A>";

        // 创建 Pattern 对象
        Pattern rGroup = Pattern.compile(patternGroup);
        Pattern rUrlIconExist = Pattern.compile(patternUrlIconExist);
        Pattern rUrlIconNotExist = Pattern.compile(patternUrlIconNotExist);

        // 生成包裹组
        UrlListDTO root = new UrlListDTO();
        String rootUuid = uuidDoUtils.uuidDoGenerate();
        root.setUuid(rootUuid);
        root.setName("导入-"+timeStampUtils.getTimestamp());
        root.setType(0);
        root.setBelong(importSubscribeDTO.getUuid());
        // root.setIcon();
        root.setIsTop(0);
        root.setCreatTime(timeStampUtils.getTimestamp());
        root.setUpdateTime(timeStampUtils.getTimestamp());
        // 录入数据库
        urlMapper.addUrlFromUrlListDTO(root);

        // 遍历html行
        for (i = 0; i < html.size(); i++) {
            // 组结构
            if (html.get(i).contains("<DT><H3")) {
                UrlListDTO tempGroup = new UrlListDTO();
                Matcher mGroup = rGroup.matcher(html.get(i));
                // 匹配成功
                if (mGroup.find()) {
                    // 组生成
                    String GroupUuid = uuidDoUtils.uuidDoGenerate();
                    tempGroup.setUuid(GroupUuid);
                    tempGroup.setName(mGroup.group(3));
                    tempGroup.setParent(rootUuid);
                    tempGroup.setType(0);
                    tempGroup.setIsTop(0);
                    tempGroup.setBelong(importSubscribeDTO.getUuid());
                    tempGroup.setCreatTime(mGroup.group(1));
                    tempGroup.setUpdateTime(mGroup.group(2));
                    root.addChild(tempGroup);
                    // 数据库录入组
                    urlMapper.addUrlFromUrlListDTO(tempGroup);
                    successNum++;
                    // 遍历组下资源列表
                    for (j = i + 1; j < html.size(); j++) {
                        if (html.get(j).contains("<DT><A HREF")) {
                            UrlListDTO tempUrl = new UrlListDTO();
                            Matcher mUrlIconExist = rUrlIconExist.matcher(html.get(j));
                            Matcher mUrlIconNotExist = rUrlIconNotExist.matcher(html.get(j));
                            if (mUrlIconExist.find()) {
                                tempUrl.setUuid(uuidDoUtils.uuidDoGenerate());
                                tempUrl.setName(mUrlIconExist.group(4));
                                tempUrl.setUrl(mUrlIconExist.group(1));
                                tempUrl.setParent(GroupUuid);
                                tempUrl.setType(1);
                                tempUrl.setBelong(importSubscribeDTO.getUuid());
                                tempUrl.setIcon(mUrlIconExist.group(3));
                                tempUrl.setIsTop(0);
                                tempUrl.setCreatTime(mUrlIconExist.group(2));
                                tempGroup.addChild(tempUrl);
                                // 数据库录入资源
                                urlMapper.addUrlFromUrlListDTO(tempUrl);
                                successNum++;
                            } else if (mUrlIconNotExist.find()) {
                                tempUrl.setUuid(uuidDoUtils.uuidDoGenerate());
                                tempUrl.setName(mUrlIconNotExist.group(3));
                                tempUrl.setUrl(mUrlIconNotExist.group(1));
                                tempUrl.setParent(GroupUuid);
                                tempUrl.setType(1);
                                tempUrl.setBelong(importSubscribeDTO.getUuid());
                                // tempUrl.setIcon(mUrlIconExist.group(3));
                                tempUrl.setIsTop(0);
                                tempUrl.setCreatTime(mUrlIconNotExist.group(2));
                                tempGroup.addChild(tempUrl);
                                // 数据库录入资源
                                urlMapper.addUrlFromUrlListDTO(tempUrl);
                                successNum++;
                            } else {
                                log.warn("导入资源时匹配失败");
                                failNum++;
                            }
                        } else if (html.get(j).contains("<DT><H3")) {
                            i = j - 1;
                            break;
                        }
                    }
                } else {
                    log.warn("导入时组匹配失败");
                    failNum++;
                }
            }
        }
        log.info("完成导入,共" + (successNum + failNum) + "项,成功" + successNum + "项,失败" + failNum + "项");
        return new ImportResultDTO(root,successNum,failNum);
    }

    @Override
    public int modifyUrl(ModifyUrlDTO modifyUrlDTO) {
        if(modifyUrlDTO.getName().length()==0 && modifyUrlDTO.getUrl().length()==0 && modifyUrlDTO.getParent().length()==0){
            return 0;
        }
        return urlMapper.modifyUrl(modifyUrlDTO);
    }

    @Override
    public int deleteUrl(DeleteUrlDTO deleteUrlDTO) {
        return urlMapper.deleteUrl(deleteUrlDTO);
    }

}
